//
//  WLButtonCountdownManager.m
//  ProjectforHDX
//
//  Created by HDX on 16/5/11.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "WLButtonCountdownManager.h"
#import "WLCountdownTask.h"

@interface WLButtonCountdownManager() {
    
 
}
@property(nonatomic,strong)    NSOperationQueue  *pool;
@end

@implementation WLButtonCountdownManager

/**
 *  获取单例
 *
 *  @return 该类的唯一实例
 */
+ (instancetype)defaultManager{
    
    static WLButtonCountdownManager *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
 
}

- (void)scheduledCountDownWithKey:(NSString *)aKey
                     timeInterval:(NSTimeInterval)timeInterval
                     countingDown:(void (^)(NSTimeInterval))countingDown
                         finished:(void (^)(NSTimeInterval))finished
{
    if (timeInterval > 120) {
        timeInterval=120;
//        NSCAssert(NO, @"受操作系统后台时间限制，倒计时时间规定不得大于 120 秒.");
    }
    
    if (_pool.operations.count >= 20)  // 最多 20 个并发线程
        return;
    
    WLCountdownTask *task = nil;
    if ([self coundownTaskExistWithKey:aKey task:&task]) {
        task.countingDownBlcok = countingDown;
        task.finishedBlcok     = finished;
        if (countingDown) {
            countingDown(task.leftTimeInterval);
        }
    } else {
        task                   = [[WLCountdownTask alloc] init];
        task.name              = aKey;
        task.leftTimeInterval  = timeInterval;
        task.countingDownBlcok = countingDown;
        task.finishedBlcok     = finished;
        [task main];
 
        [_pool addOperation:task];
    }
}


- (BOOL)coundownTaskExistWithKey:(NSString *)akey
                            task:(NSOperation *__autoreleasing  _Nullable *)task
{
    __block BOOL taskExist = NO;
    [_pool.operations enumerateObjectsUsingBlock:^(__kindof NSOperation * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.name isEqualToString:akey]) {
            if (task) *task = obj;
            taskExist = YES;
            *stop     = YES;
        }
    }];
    
    return taskExist;
}

@end
